package com.yueyin.ui.main;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.yueyin.MainActivity.FragmentCatalog;
import com.yueyin.MainActivity.FragmentMain;
import com.yueyin.R;

import java.io.IOException;
import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class PlayLogic extends AppCompatActivity {

    Context context;
    FragmentMain fragmentMain;
    FragmentCatalog fragmentCatalog;

    //play order 默认模式为random
    private String playModel = "random";

    //当前播放音乐
    private String currentMusicName;

    //当前歌曲在列表中的位置
    public int position = -1;

    //当前播放状态
    private boolean isPlaying = false;

    private boolean threadFlag = true;

    private Calendar calendar = Calendar.getInstance();

    //获取列表中歌曲总数
    private Integer totalMusicNum = -1;

    private MediaPlayer media;

    public Handler handler;

    Thread thread;


    public PlayLogic(Context context) {
        this.context = context;

        if (media == null) {
            media = new MediaPlayer();
        }

        if (thread == null) {
            thread = new Thread(new MediaThread());
            thread.setDaemon(true);
            thread.start();
        }
    }

    public MediaPlayer getMedia() {
        return media;
    }

    public void setFragmentMain(FragmentMain fragmentMain) {
        this.fragmentMain = fragmentMain;
    }

    public void setFragmentCatalog(FragmentCatalog fragmentCatalog) {
        this.fragmentCatalog = fragmentCatalog;
    }

    public void setTotalMusicNum(Integer totalMusicNum) {
        this.totalMusicNum = totalMusicNum;
    }

    /**
     * 上一曲
     */
    public void lastMusic() {
        if ("random".equals(this.getPlayModel())) {
            int targetPosition = new Random().nextInt(totalMusicNum);

            if (targetPosition != this.position) {
                this.position = targetPosition;
                this.resetStart(this.position, true);
            } else {
                lastMusic();
            }
        } else {
            if (this.position < 1) {
                this.position = totalMusicNum - 1;
            } else {
                this.position--;
            }

            this.resetStart(this.position, true);
        }
    }

    /**
     * 下一曲
     */
    public void nextMusic() {
        if ("random".equals(this.getPlayModel())) {
            int targetPosition = new Random().nextInt(totalMusicNum);

            if (targetPosition != this.position) {
                this.position = targetPosition;
                this.resetStart(this.position, true);
            } else {
                nextMusic();//若随机的下一曲与当前相同，再次随机
            }
        } else {
            if (this.position < totalMusicNum - 1) {
                this.position += 1;
            } else {
                this.position = 0;
            }

            this.resetStart(this.position, true);
        }

    }

    /**
     * 播放、暂停
     */
    public void playOrPause(boolean b) {
        if (media.isPlaying() && b) {
            fragmentMain.binding.ivPlayPause.setImageResource(R.mipmap.play);
            media.pause();
            isPlaying = false;
        } else if (b) {
            this.resetStart(0, false);
            isPlaying = true;
        } else {
            media.pause();
        }
    }

    public class MediaThread implements Runnable {
        @Override
        public void run() {

            media.setOnCompletionListener(mediaPlayer -> {
                if (!mediaPlayer.isPlaying()) {
                    if (!mediaPlayer.isLooping())
                        nextMusic();
                    else
                        resetStart(0, false);
                }
            });
        }
    }

    /**
     * 切换播放模式
     */
    public void changePlayModel() {

        switch (this.getPlayModel()) {
            case "random":
                this.setPlayModel("order");
                media.setLooping(true);
                fragmentMain.binding.ivPlayModel.setImageResource(R.mipmap.order);
                Toast.makeText(context, "顺序播放 ！", Toast.LENGTH_SHORT).show();
                break;

            case "order":
                media.setLooping(true);
                this.setPlayModel("single");
                fragmentMain.binding.ivPlayModel.setImageResource(R.mipmap.single);
                Toast.makeText(context, "单曲循环 ！", Toast.LENGTH_SHORT).show();
                break;

            case "single":
                this.setPlayModel("random");
                media.setLooping(false);
                fragmentMain.binding.ivPlayModel.setImageResource(R.mipmap.random);
                Toast.makeText(context, "随机播放 ！", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 歌曲播放进度效果
     */
    public void showTimes() {
        //总时长
        calendar.setTimeInMillis(media.getDuration());

        final int hours = calendar.get(Calendar.HOUR);
        final int minutes = calendar.get(Calendar.MINUTE);
        final int seconds = calendar.get(Calendar.SECOND);


        //播放面板显示总时长
        String time;

        if (seconds < 10)
            time = minutes + ":0" + seconds;
        else
            time = minutes + ":" + seconds;

        fragmentMain.binding.TVTotalTime.setText(time);

        //接收Message 用于更新当前播放进度（时间显示和进度条显示）
        handler = new Handler(msg -> {
            int i = media.getCurrentPosition();

            String nowTime;

            if (i / 1000 % 60 < 10)
                nowTime = i / 1000 / 60 + ":0" + i / 1000 % 60;
            else
                nowTime = i / 1000 / 60 + ":" + i / 1000 % 60;

            fragmentMain.binding.TVNowTime.setText(nowTime);

            //更新进度条进度
            fragmentMain.binding.SK.setProgress(i * fragmentMain.binding.SK.getMax() / media.getDuration());
            return true;
        });

        Thread thread = new Thread(() -> {
            while (media.isPlaying()) {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendMessage(new Message());
            }
        });

        thread.setDaemon(true);
        thread.start();
    }


    /**
     * 重置播放器状态并播放当前选中曲目
     *
     * @param currentPosition 当前播放位置
     * @param flag            true:重置歌曲并播放
     *                        false:开始播放（结束暂停状态）
     */
    public void resetStart(int currentPosition, boolean flag) {

        if (flag) {
            Data data = fragmentCatalog.dataList.get(currentPosition);

            String musicName = data.getName();
            this.setCurrentMusicName(musicName);
            position = currentPosition;
            media.reset();
            Cursor cursor = new SQLiteHelper(context).findByName(musicName, false);
            cursor.moveToFirst();

            int index = cursor.getColumnIndex("path");
            String path = cursor.getString(index > -1 ? index : 0);
            cursor.close();

            try {
                media.setDataSource(path);
                media.prepare();
            } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }

        media.start();

        showTimes();
        //每次开始播放重置播放按钮图标
        fragmentMain.binding.ivPlayPause.setImageResource(R.mipmap.pause);
        //播放面板显示当前歌曲名
        fragmentMain.binding.tvMusicName.setText(getCurrentMusicName());
    }

    public String getPlayModel() {
        return playModel;
    }

    public void setPlayModel(String playModel) {
        this.playModel = playModel;
    }

    public String getCurrentMusicName() {
        return currentMusicName;
    }

    public void setCurrentMusicName(String currentMusicName) {
        this.currentMusicName = currentMusicName;
    }
}
